<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>首页banner图</span>
        <el-button style="float:right" type="primary" @click="handleAdd" size="small">
          添加广告
        </el-button>
      </div>
    </el-card>

    <div class="table-container">
      <el-table :data="list" style="width: 100%;" v-loading="listLoading" border>
        <el-table-column label="ID" width="80" align="center">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="广告名称" align="center">
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column label="广告链接" align="center">
          <template slot-scope="scope">{{ scope.row.link || '-' }}</template>
        </el-table-column>
        <el-table-column label="排序号" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.sort }}</template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper" :page-size="listQuery.pageSize" :page-sizes="[5, 10, 15]"
        :current-page.sync="listQuery.pageNum" :total="total">
      </el-pagination>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="isEdit ? '编辑广告' : '新建广告'" :visible.sync="dialogVisible" width="700px" :close-on-click-modal="false" :close-on-press-escape="true">
      <el-form :model="advertisement" :rules="rules" ref="advertisementForm" label-width="120px">
        <el-form-item label="广告名称" prop="name">
          <el-input v-model="advertisement.name" placeholder="请输入广告名称"></el-input>
        </el-form-item>
        <el-form-item label="广告链接" prop="link">
          <el-input v-model="advertisement.link" placeholder="请输入广告链接"></el-input>
        </el-form-item>
        <el-form-item label="广告图片" prop="image">
          <el-upload class="avatar-uploader" action="#" :show-file-list="false" :http-request="handleUpload"
            :before-upload="beforeUpload">
            <div v-if="advertisement.image" class="avatar-wrapper">
              <img :src="advertisement.image" class="avatar">
              <div class="avatar-mask" @click.stop>
                <i class="el-icon-edit" @click="handleReplaceImage"></i>
                <i class="el-icon-delete" @click="handleRemoveImage" style="margin-left: 20px;"></i>
              </div>
            </div>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="upload-tip">2M以内png、jpg，尺寸750*246</div>
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input-number v-model="advertisement.sort" :min="0" placeholder="请输入排序号"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" :disabled="submitLoading">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchAdvertisementList, createAdvertisement, updateAdvertisement, deleteAdvertisement, uploadImage } from '@/api/content'

export default {
  name: 'advertisementList',
  data() {
    return {
      listQuery: {
        pageNum: 1,
        pageSize: 10
      },
      list: [],
      total: 0,
      listLoading: false,
      submitLoading: false,
      dialogVisible: false,
      isEdit: false,
      advertisement: {
        name: '',
        link: '',
        image: '',
        sort: 0
      },
      rules: {
        name: [
          { required: true, message: '请输入广告名称', trigger: 'blur' }
        ],
        link: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback()
                return
              }
              // 简化的URL验证，支持http、https协议或者相对路径
              const urlPattern = /^(https?:\/\/.*|\/.*)$/i
              if (!urlPattern.test(value)) {
                callback(new Error('请输入正确的链接地址，以http://或https://开头'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleRemoveImage() {
      this.$confirm('确定要删除这张图片吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.advertisement.image = ''
        this.$message.success('删除成功')
      }).catch(() => {
        // 用户取消删除
      })
    },
    handleReplaceImage() {
      // 触发文件选择
      const uploadInput = document.querySelector('.avatar-uploader input[type="file"]')
      if (uploadInput) {
        uploadInput.click()
      }
    },
    getList() {
      this.listLoading = true
      fetchAdvertisementList(this.listQuery).then(response => {
        this.listLoading = false
        this.list = response.data.data
        this.total = response.data.total
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val
      this.getList()
    },
    handleAdd() {
      this.isEdit = false
      this.advertisement = {
        name: '',
        link: '',
        image: '',
        sort: 0
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.advertisementForm.clearValidate()
      })
    },
    handleUpdate(row) {
      this.isEdit = true
      this.advertisement = {
        id: row.id,
        name: row.name,
        link: row.link,
        image: row.image,
        sort: row.sort
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.advertisementForm.clearValidate()
      })
    },
    handleSubmit() {
      this.$refs.advertisementForm.validate(valid => {
        if (valid) {
          this.submitLoading = true
          const request = this.isEdit
            ? updateAdvertisement(this.advertisement.id, this.advertisement)
            : createAdvertisement(this.advertisement)

          request.then(() => {
            this.submitLoading = false
            this.$message.success(this.isEdit ? '更新成功' : '创建成功')
            this.dialogVisible = false
            this.getList()
          }).catch(() => {
            this.submitLoading = false
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确定要删除该广告吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAdvertisement(row.id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    beforeUpload(file) {
      const isImage = file.type.indexOf('image/') === 0
      const isLt2M = file.size / 1024 / 1024 < 2
      
      // 检查文件类型是否为PNG或JPG
      const isPNG = file.type === 'image/png'
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg'
      
      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      
      if (!isPNG && !isJPG) {
        this.$message.error('只支持PNG和JPG格式的图片!')
        return false
      }
      
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
        return false
      }
      
      // 直接返回true，不再检查尺寸
      return true
    },
    handleUpload(params) {
      const loading = this.$loading({
        lock: true,
        text: '上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      uploadImage(params.file).then(response => {
        console.log('===== 上传调试开始 =====')
        console.log('上传响应:', response)
        
        if (response && response.data) {
          console.log('响应数据:', response.data)
          console.log('后端返回的URL:', response.data.url)
          
          if (response.data.url) {
            // 确保URL格式正确
            let imageUrl = response.data.url
            console.log('处理前的imageUrl:', imageUrl)
            
            // 处理各种可能的URL格式
            if (imageUrl && !imageUrl.startsWith('http://') && !imageUrl.startsWith('https://')) {
              console.log('URL不是完整地址，需要处理')
              
              // 检查环境变量
              console.log('API_BASE_URL环境变量:', process.env.API_BASE_URL)
              
              // 强制使用API_BASE_URL作为基础URL，不回退到window.location.origin
              const baseUrl = process.env.API_BASE_URL
              console.log('使用的baseUrl:', baseUrl)
              
              if (baseUrl) {
                // 确保baseUrl不以/结尾，避免重复斜杠
                const cleanBaseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl
                
                // 确保imageUrl以/开头
                const cleanImageUrl = imageUrl.startsWith('/') ? imageUrl : '/' + imageUrl
                
                // 拼接完整URL
                imageUrl = cleanBaseUrl + cleanImageUrl
                console.log('添加域名后的imageUrl:', imageUrl)
              } else {
                console.error('API_BASE_URL未配置')
                this.$message.error('API_BASE_URL未配置，无法构建完整图片URL')
              }
              
              // 移除多余的提示
            } else {
              console.log('URL已是完整地址，无需添加域名')
            }
            
            this.advertisement.image = imageUrl
            console.log('最终设置的图片URL:', this.advertisement.image)
          } else {
            this.$message.error('获取图片URL失败')
            console.error('URL字段为空或不存在')
          }
        } else {
          this.$message.error('响应数据格式不正确')
          console.error('响应格式错误:', response)
        }
        
        console.log('===== 上传调试结束 =====')
        loading.close()
        this.$message.success('上传成功')
      }).catch((error) => {
        loading.close()
        console.error('上传失败:', error)
        this.$message.error('上传失败: ' + (error.message || '未知错误'))
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    display: inline-block;
    width: 375px;
    height: 123px;
  }

  .avatar-uploader:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 375px;
    height: 123px;
    line-height: 123px;
    text-align: center;
    display: block;
  }

.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: contain;
  background-color: #f5f5f5;
}

.avatar-wrapper {
  position: relative;
  width: 375px;
  height: 123px;
  overflow: hidden;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background-color: #f5f5f5;
}

.avatar-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
  cursor: pointer;
  z-index: 10;
}

.avatar-wrapper:hover .avatar-mask {
  opacity: 1;
}

.avatar-mask .el-icon-edit,
.avatar-mask .el-icon-delete {
  color: white;
  font-size: 24px;
  margin: 0 10px;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>
